﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DevComponents.DotNetBar;
using System.Windows.Forms;
using SuperMap.Data;
using SuperMap.Realspace;
using System.Diagnostics;
using Shine.Util;
using Shine.Framework;

namespace Shine.SchemaManager
{
    public partial class ProjectListForm : Office2007Form
    {
        //private static ProjectListForm instance_list_form = null;
        private ProjectItemForm instance_item_form = null;
        private ViewItemForm instance_viewer_form = null;
        private UpdateItemForm instance_update_form = null;

        private Scene scene= null;
        private Workspace workspace = null;
        private IApplication application = null;
        private DatasourceConnectionInfo datasourceInfo = null;

        private int currentProjectSelectedRowId = 0;
        private string currentSelectedProjectName = string.Empty; // 项目名称和udd的名称是一致的

        private int currentSchemeSelectedRowId = 0;
        private string currentSelectedSchemeName = string.Empty; // 当前模型名称

        private 规划项目 project = null; // 当前的方案对象

        public ProjectListForm(Scene _scene, Workspace _ws, IApplication _app)
        {
            // TODO: Complete member initialization
            InitializeComponent();
            this.scene = _scene;
            this.workspace = _ws;
            this.application = _app;
        }

        //public static ProjectListForm GetInstance(Scene _scene, Workspace _ws, IApplication _app) 
        //{ 
        //    if(instance_list_form == null || instance_list_form.IsDisposed)
        //    {
        //        instance_list_form = new ProjectListForm(_scene,_ws,_app);
        //    }
        //    return instance_list_form;
        //}

        /// <summary>
        /// 加载项目方案
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenBtn_Click(object sender, EventArgs e)
        {
            // 加载项目文件（*.xml）
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "请选择项目方案……";
            fdlg.InitialDirectory = @"c:\";
            fdlg.Filter = "All files(*.xml) | *.xml";
            fdlg.FilterIndex = 0;
            fdlg.RestoreDirectory = false;
            if(fdlg.ShowDialog() == DialogResult.OK)
            {
                // 加载方案内容
                string projectFile = fdlg.FileName;
                规划项目 project = Shine.Util.Configurations.ConfigurationHelper.GetObjectFromXml<规划项目>(projectFile);
                // 添加新记录
                AddNewProject(project);
            }
            
        }

        /// <summary>
        /// DataGridView插入项目记录
        /// </summary>
        /// <param name="project"></param>
        private void AddNewProject(规划项目 project)
        {
            DataGridViewRow dr = new DataGridViewRow();
            dr.Tag = project;

            DataGridViewTextBoxCell prjName = new DataGridViewTextBoxCell();
            prjName.Value = project.ProjectName;
            dr.Cells.Add(prjName);
            
            DataGridViewButtonCell viewDetails = new DataGridViewButtonCell();
            viewDetails.Value = "查看";
            dr.Cells.Add(viewDetails);

            DataGridViewButtonCell modifyInfos = new DataGridViewButtonCell();
            modifyInfos.Value = "编辑";
            dr.Cells.Add(modifyInfos);

            DataGridViewCheckBoxCell loadUDD = new DataGridViewCheckBoxCell();
            loadUDD.Value = false; 
            dr.Cells.Add(loadUDD);

            dgvProjectList.Rows.Add(dr);
        }

        /// <summary>
        /// 修改项目信息后更新项目记录
        /// </summary>
        /// <param name="project"></param>
        private void UpdateProjectInfo(规划项目 project)
        {
            DataGridViewRow dr = this.dgvProjectList.Rows[currentProjectSelectedRowId];
            string LastName = ((规划项目)dr.Tag).ProjectName;
            dr.Cells[0].Value = project.ProjectName;
            this.currentSelectedProjectName = project.ProjectName;

            // 更新数据源的名字
            if(string.Compare(LastName,project.ProjectName) != 0)
            {
                this.workspace.Datasources.ModifyAlias(LastName, project.ProjectName);
                this.workspace.Datasources[project.ProjectName].Refresh();
            }
            
            // 更新row's tag
            dr.Tag = project;
        }

        /// <summary>
        /// DataGridView插入方案记录
        /// </summary>
        private void AddNewScheme(Dataset dataset)
        {
            DataGridViewRow dr = new DataGridViewRow();
            dr.Tag = dataset.Name;

            DataGridViewTextBoxCell schemeName = new DataGridViewTextBoxCell();
            schemeName.Value = dataset.Name;
            dr.Cells.Add(schemeName);

            DataGridViewCheckBoxCell loadScheme = new DataGridViewCheckBoxCell();
            loadScheme.Value = false;
            dr.Cells.Add(loadScheme);

            dgvShemeList.Rows.Add(dr);
        }

        /// <summary>
        /// 读取数据源*.udd里的数据集
        /// </summary>
        /// <param name="udd"></param>
        private void FillDataSetFromDataSource(string datasetName)
        {
            Datasets dataSets = this.workspace.Datasources[datasetName].Datasets;
            foreach(Dataset ds in dataSets)
            {
                this.AddNewScheme(ds);
            }
        }

        private void NewBtn_Click(object sender, EventArgs e)
        {
            this.instance_item_form = ProjectItemForm.GetInstance();
            this.instance_item_form.getDelegateHandler = this.AddNewProject;
            this.instance_item_form.ShowDialog(this);
        }

        private void ProjectListForm_Load(object sender, EventArgs e)
        {
            datasourceInfo = new DatasourceConnectionInfo();
            datasourceInfo.EngineType = EngineType.UDB;
        }

        /// <summary>
        /// 当前工作空间加载指定数据源
        /// </summary>
        /// <param name="_datasourceInfo"></param>
        private void OpenDatasource(DatasourceConnectionInfo _datasourceInfo)
        {
            //this.workspace.Datasources.CloseAll();
            if(this.workspace != null)
            {
                Datasource datasource = this.workspace.Datasources.Open(_datasourceInfo);
                if(datasource != null)
                {
                    MessageBox.Show(string.Format("加载设计方案文件成功！"),"提示",MessageBoxButtons.OK);
                }
                else
                {
                    MessageBox.Show(string.Format("加载设计方案失败！"),"提示",MessageBoxButtons.OK);
                }
            }
            else
            {
                MessageBox.Show(string.Format("当前工作空间打开失败！"),"提示",MessageBoxButtons.OK);
            }
        }

        /// <summary>
        /// 当前工作空间加载指定数据源
        /// </summary>
        /// <param name="file">udd文件路径</param>
        private void LoadDatasource(string file,string aliasName)
        {
            datasourceInfo.Server = file;
            datasourceInfo.Alias = aliasName;
            // 检测当前workspace里是否已经添加改数据源
            bool isExist = this.CheckIfDataSourceIsExist(datasourceInfo);
            if (!isExist)
            {
                this.OpenDatasource(datasourceInfo);
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 检测当前workspace里是否已经存在该数据源
        /// </summary>
        /// <param name="datasourceInfo"></param>
        private bool CheckIfDataSourceIsExist(DatasourceConnectionInfo _datasourceInfo)
        {
            //throw new NotImplementedException();
            if (this.workspace != null)
            {
                if (this.workspace.Datasources.Contains(_datasourceInfo.Alias))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                MessageBox.Show(string.Format("当前工作空间打开失败！"), "提示", MessageBoxButtons.OK);
                return false;
            }
        }

        /// <summary>
        /// 从workspace中移除*.udd数据集
        /// </summary>
        /// <param name="p"></param>
        private void RemoveDataSetFromDataSource(string datasourceName)
        {
            if (this.workspace.Datasources[datasourceName] != null)
            {
                // 移除当前数据源的图层
                Datasets dataSets = this.workspace.Datasources[datasourceName].Datasets;
                foreach (Dataset ds in dataSets)
                {
                    Layer3DVectorFile datasetModel = null;
                    string fullName = ds.Name + "@" + datasourceName;
                    try
                    {
                        if (this.scene.Layers.Contains(fullName))
                        {
                            this.scene.Layers.Remove(fullName);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.StackTrace);
                    }
                }
                this.scene.Refresh();
                this.workspace.Datasources[datasourceName].Close();
                MessageBox.Show(string.Format("数据集:{0}，已关闭!", datasourceName));
            }
        }

        /// <summary>
        /// 点击Row的内容栏，触发以下事件：
        /// 1. 点击第一栏，获取项目里的方案，在右侧方案列表中展示，并加载该方案
        /// 2. 点击第二栏，触发查看方案事件
        /// 3. 点击第三栏，触发修改方案事件
        /// 4. 点击第四栏，加载当前方案的UDD
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvProjectList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowId = e.RowIndex;
            int columnId = e.ColumnIndex;
            currentProjectSelectedRowId = rowId;

            this.project = (规划项目)(dgvProjectList.Rows[rowId].Tag);
            this.currentSelectedProjectName = this.project.ProjectName;

            if(columnId == 0) // 点击第一栏
            {
                if(!(bool)this.dgvProjectList.Rows[rowId].Cells[3].Value)
                {
                    this.dgvProjectList.Rows[rowId].Cells[3].Value = true;
                }
            }
            else if(columnId == 1) // 点击查看方案
            {
                // 查看项目信息
                this.instance_viewer_form = ViewItemForm.GetInstance(this.project);
                this.instance_viewer_form.ShowDialog(this);
            }
            else if (columnId == 2) // 点击修改方案
            {
                // 修改项目信息
                this.instance_update_form = UpdateItemForm.GetInstance(this.project);
                this.instance_update_form.getDelegateHandler = this.UpdateProjectInfo;
                this.instance_update_form.ShowDialog(this);
            }
            else // 点击加载方案
            {
                bool flag = (bool)this.dgvProjectList.Rows[rowId].Cells[3].Value;
                if (flag)
                {
                    this.dgvProjectList.Rows[rowId].Cells[3].Value = false;
                }
                else
                {
                    this.dgvProjectList.Rows[rowId].Cells[3].Value = true;
                }
            }
        }

        /// <summary>
        /// 点击Row的内容栏，触发以下事件：
        /// 1. 点击第二栏，把模型加载到当前scene
        /// 2. 点击第三栏，把模型从当前scene移除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvShemeList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int rowId = e.RowIndex;
            currentSchemeSelectedRowId = rowId;
            int columnId = e.ColumnIndex;
            this.currentSelectedSchemeName = dgvShemeList.Rows[currentSchemeSelectedRowId].Tag.ToString();

            if (columnId == 1) // 点击加载模型
            {
                bool flag = (bool)this.dgvShemeList.Rows[rowId].Cells[1].Value;

                if (flag)
                {
                    this.dgvShemeList.Rows[rowId].Cells[1].Value = false;
                }
                else
                {
                    this.dgvShemeList.Rows[rowId].Cells[1].Value = true;
                }
            }

        }

        /// <summary>
        /// 加载数据源中指定数据集到三维场景中
        /// </summary>
        /// <param name="datasetName"></param>
        private void AddModelSchemeToScene(string datasetName)
        {
            string fullName = datasetName + "@" + this.currentSelectedProjectName;
            try
            {
                if (this.currentSelectedProjectName.Length > 0 && this.currentSelectedProjectName != null)
                {
                    if (!this.scene.Layers.Contains(fullName))
                    {
                        DatasetVector datasetModel = this.workspace.Datasources[this.currentSelectedProjectName].Datasets[datasetName] as DatasetVector;
                        Layer3DSettingVector settingVector = new Layer3DSettingVector();
                        settingVector.Style.AltitudeMode = AltitudeMode.Absolute;

                        try
                        {
                            this.scene.Layers.Add(datasetModel, settingVector, true);
                            this.scene.Refresh();
                            MessageBox.Show(string.Format("成功加载数据集{0}", datasetName));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.StackTrace);
                        }
                    }

                    this.scene.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
            }

        }

        /// <summary>
        /// 移除当前三维场景中制定数据集
        /// </summary>
        /// <param name="datasetName"></param>
        private void RemoveModelSchemeFromScene(string datasetName)
        {
            Layer3DVectorFile datasetModel = null;
            string fullName = datasetName + "@" + this.currentSelectedProjectName;
            try
            {
                if (this.currentSelectedProjectName.Length > 0 && this.currentSelectedProjectName != null)
                {
                    if(this.scene.Layers.Contains(fullName))
                    {
                        this.scene.Layers.Remove(fullName);
                        MessageBox.Show(string.Format("成功移除数据集{0}", datasetName));
                    }
                    this.scene.Refresh();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
            }
        }

        private void ProjectListForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            /// TODO
        }

        /// <summary>
        /// 加载方案的checkbox变化时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvProjectList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvProjectList.Rows.Count == 0)
            {
                return;
            }

            if (e.ColumnIndex == 3)
            {
                bool flag = (bool)this.dgvProjectList.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue;
                // 选中checkbox
                if (flag)
                {
                    // 项目对应的udd自动加载到当前工作空间的数据源中e
                    this.LoadDatasource(this.project.Path, this.project.ProjectName);

                    // 获取项目里的方案集合，加载到右侧方案列表
                    this.dgvShemeList.Rows.Clear();
                    this.FillDataSetFromDataSource(this.project.ProjectName);
                }
                else
                {
                    // 清除右侧项目方案集合
                    this.dgvShemeList.Rows.Clear();
                    // 从workspace里移除
                    this.RemoveDataSetFromDataSource(this.project.ProjectName);
                }
            }
        }

        private void ProjectListForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.dgvProjectList.Rows.Clear();
            this.dgvShemeList.Rows.Clear();
            this.Dispose();
        }

        private void dgvShemeList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvShemeList.Rows.Count == 0)
            {
                return;
            }

            int rowId = e.RowIndex;
            this.currentSchemeSelectedRowId = rowId;

            int columnId = e.ColumnIndex;
            this.currentSelectedSchemeName = dgvShemeList.Rows[currentSchemeSelectedRowId].Tag.ToString();

            if (this.dgvShemeList.Rows.Count == 0)
            {
                return;
            }

            if (e.ColumnIndex == 1)
            {
                bool flag = (bool)this.dgvShemeList.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue;

                // 选中checkbox
                if (flag)
                {
                    // 加载当前模型方案
                    this.AddModelSchemeToScene(this.currentSelectedSchemeName);
                }
                else
                {
                    // 卸载当前模型方案
                    this.RemoveModelSchemeFromScene(this.currentSelectedSchemeName);
                }
            }
        }

    }
}
